﻿using Docx2Epub.Docx;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Docx2Epub.Epub
{
    public class EpubBuilder
    {
        private List<DocElement> elements;
        private EPubMetadatas metadatas;

        public EpubBuilder(IEnumerable<DocElement> elements, EPubMetadatas metadatas)
        {
            this.elements = elements.ToList();
            this.metadatas = metadatas;
        }

        public void WriteOut(string outputPath)
        {
            copyTemplate(outputPath);

            // create content.odf
            new EpubOpfWriter(outputPath, 
                elements.Where(e => e is DocChapter).Select(e => (DocChapter)e), 
                metadatas).WriteOut();

            // create toc.ncx
            new EpubNavigationWriter(outputPath, elements, metadatas).WriteOut();

            // create nav.xhtml
            new EpubNavigationXhtmlWriter(outputPath, elements, metadatas).WriteOut();

            // create cover.xhtml
            new EPubCoverWriter(outputPath, metadatas).WriteOut();

            // create chapters
            new EpubChapterGenerator(outputPath, elements, metadatas).GenerateAll();
        }

        private void copyTemplate(string outputPath)
        {
            //Now Create all of the directories
            foreach (string dirPath in Directory.GetDirectories(metadatas.TemplateDirectory, "*",
                SearchOption.AllDirectories))
                Directory.CreateDirectory(dirPath.Replace(metadatas.TemplateDirectory, outputPath));

            //Copy all the files & Replaces any files with the same name
            foreach (string newPath in Directory.GetFiles(metadatas.TemplateDirectory, "*.*",
                SearchOption.AllDirectories))
                File.Copy(newPath, newPath.Replace(metadatas.TemplateDirectory, outputPath), true);
        }

    }
}
